using UnityEngine;
using System.Collections;

public class CheckPointMgr : MonoBehaviour {
	
	public float rayLength{get;set;}
	public static CheckPointMgr Instance;
	private Vector3 _startPos, _moveDirection, _verticalDirection;
	private bool _isClockwise;
	private int _currentCKPIndex;
	public GameObject mainCharacter;
	private ArrayList checkpointList;
	// Use this for initialization
	void Awake () {
		_currentCKPIndex = -1;
		Instance = this;
		checkpointList = new ArrayList();		
	}
	
	void Start(){
		_startPos = GameObject.Find("MainCharacter").transform.position;
		_moveDirection = GameObject.Find("MainCharacter").GetComponent<MainCharacterController>().moveDirection;
		_verticalDirection = GameObject.Find("MainCharacter").GetComponent<MainCharacterController>().verticalDirection;
		_isClockwise = GameObject.Find("MainCharacter").GetComponent<MainCharacterController>().isClockwise;
		rayLength = GameObject.Find("MainCharacter").GetComponent<MainCharacterController>().jumpHeight;
	}
	// Update is called once per frame
	void Update () {
	
	}
	
	public void RegisterCheckpoints(CheckPoint ckp){
		checkpointList.Add(ckp);
		ckp.index = checkpointList.Count - 1;
//		Debug.LogError(ckp.gameObject.name + ckp.index);
	}
	
	public void UpdateCurrentCKP(int currentIndex)
	{
		_currentCKPIndex = currentIndex;
	}
	
	public void Respawn()
	{	
		if(_currentCKPIndex >= 0)
			(checkpointList[_currentCKPIndex] as CheckPoint).Respawn();
		else
			StartCoroutine(RespawnAtStartPnt());
	}
	
	IEnumerator RespawnAtStartPnt()
	{
	//	Debug.Log("respawn at start pnt");
		CameraMovment.Instance.SetCameraToRespawnPoint(transform.position.x, transform.position.y);
		yield return new WaitForSeconds(1.0f);
		GameObject main = Instantiate(mainCharacter, _startPos, Quaternion.identity) as GameObject;
		main.GetComponent<MainCharacterController>().moveDirection = _moveDirection;
		main.GetComponent<MainCharacterController>().verticalDirection = _verticalDirection;
		main.GetComponent<MainCharacterController>().isClockwise = _isClockwise;
		CameraMovment.Instance.SetMainCtrl(main.GetComponent<MainCharacterController>());
	}
}
